package cn.template.services;

import cn.template.models.Company;
import cn.template.models.CompanyRepository;
import cn.template.models.exceptions.DatabaseOperationException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;


@Service
public class CompanyService extends BaseService<CompanyRepository, Company> {
    @Autowired
    public void setTheRepository(CompanyRepository repository) {
        this.setRepository(repository);
    }

    public Page<Company> getByName(int page, int size, String name) {
        try {
            CompanyRepository repository = this.getRepository();
            return name == null || name.isEmpty() ?
                    repository.findAll(this.getPageable(page, size)) :
                    repository.findByNameLike(fuzzy(name), this.getPageable(page, size, "name", Sort.Direction.ASC));
        } catch (RuntimeException ex) {
            throw new DatabaseOperationException("Fail to query company by name", ex);
        }
    }

}
